import { PROJECTNAME } from '../globalData'
import { setRequestData, setRequestHeader } from './requestDefaultParams'
import { decodeByDES, str2EncodeByDES } from '../tripledes'
import { setStorageSync } from '../handlers'

const postLogin = (jsCode, globalData, resolve) => {
    wx.request({
        url: `${PROJECTNAME}/restaurant-user/user/shakeHands`,
        data: setRequestData(),
        header: setRequestHeader(),
        method: 'POST',
        success: function (res) {
            const { data } = res;
            let result = decodeByDES(data.srs);
            console.log(`PROJECTNAME: ${PROJECTNAME}`);
            console.log('shakeHands:');
            console.log(result);
            wx.request({
                url: `${PROJECTNAME}/restaurant-user/user/doLogin`,
                data: setRequestData({
                    pdata: null,
                    sdt: str2EncodeByDES({ loginType: 'WEI_CHAT', account: jsCode }, result.loginKey)
                }),
                header: setRequestHeader({ sessionId: result.shakeHandsId }),
                method: 'POST',
                success: function (subRes) {
                    const { data: subData } = subRes;
                    let loginInfo = decodeByDES(subData.srs);
                    console.log('doLogin:');
                    console.log(loginInfo);
                    setStorageSync('phone', loginInfo.loginedUser.phoneNo);
                    globalData.loginInfo = loginInfo;
                    resolve(loginInfo)
                }
            });
        },
        fail: function () {

        },
        complete: function () {

        },
    })
};

module.exports = {
    postLogin
};